// router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import Login from '../views/login.vue';
import Index from '../views/index.vue';
import Home from '../views/home.vue';
import SocialPractice from '@/views/socialPractice.vue';
import Student from '@/views/student.vue';
import BreakTheRule from '@/views/BreakTheRule.vue';
import StudentScore from '@/views/studentScore.vue';
import Server from '@/views/monitorServer.vue';
import { useAuthStore } from '@/stores/auth';

const routes = [
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/',
    name: 'index',
    component: Index,
    redirect: '/server',
    meta: { breadcrumb: '首页' },
    children: [
      {
        path: 'home',
        name: 'home',
        component: Home
      },
      {
        path: 'socialPractice',
        name: 'socialPractice',
        component: SocialPractice,
        meta: { breadcrumb: '社会实践', requiresAuth: true }
      },
      {
        path: 'breakTheRule',
        name: 'breakTheRule',
        component: BreakTheRule,
        meta: { breadcrumb: '违纪情况', requiresAuth: true }
      },
      {
        path: 'studentScore',
        name: 'studentScore',
        component: StudentScore,
        meta: { breadcrumb: '学生详细信息', requiresAuth: true }
      },
      {
        path: 'student',
        name: 'student',
        component: Student,
        meta: { breadcrumb: '学生成绩', requiresAuth: true }
      },
      {
        path: 'server',
        name: 'server',
        component: Server,
        meta: { breadcrumb: '电脑信息', requiresAuth: true }
      },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
});

router.beforeEach((to, from, next) => {
  const authStore = useAuthStore();
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  const token = sessionStorage.getItem('Token');
  if (requiresAuth && ! token) {
    console.log('重定位到 /login');
    next('/login');
  } else {
    console.log('没有重定位');
    next();
  }
});

export default router;